package cn.catsdad.auth.handle;

import cn.catsdad.base.web.HttpResponse;
import cn.catsdad.constant.iConstant.IResponseStatus;
import cn.catsdad.util.JsonUtil;
import cn.catsdad.util.ServletUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * 认证失败处理类
 *
 * @author xuyonglong
 * @version V1.0 2023/4/14
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        int code = IResponseStatus.UNAUTHORIZED;
        String msg = String.format("请求访问：{%s}，认证失败，无法访问系统资源", request.getRequestURI());
        HttpResponse<String> result = new HttpResponse<>();
        result.setStatus(code);
        result.setSuccess(false);
        result.setMsg(msg);
        ServletUtil.renderString(response, JsonUtil.toJsonStr(result));
    }
}
